package pri.hillchen.std.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 13:35 2018/3/30 0030.
 */
public class TimeServerHandler implements Runnable {
    public static final String QUERY_TIME_COMMAND = "CURRENT_TIME";
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stop;
    public TimeServerHandler(int port) throws IOException {
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(port),1024);

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("server is start in port:" + port);
    }

    @Override
    public void run() {
        while (!stop){
            try{
                //多路复用选择器等待指定时间来获取请求信息
                System.out.println("等待就绪请求集:" + selector.select(1000));
                Set<SelectionKey> selectionKeys = selector.selectedKeys();

                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()){
                    key = it.next();
                    it.remove();
                    try{
                        handleReady(key);
                    }catch (Exception e){
                        if(key != null){
                            key.cancel();
                            if(key.channel() != null){
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(selector != null){
            try {
                selector.close();
                selector = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理准备就绪了的key
     * @param key
     */
    private void handleReady(SelectionKey key) throws IOException {
        //判断当前key是否有效
        if(key.isValid()){
            if(key.isAcceptable()){
                handleAccept(key);
            }else if(key.isReadable()){
                handleRead(key);
            }
        }
    }

    /**
     * 处理连接请求
     * @param key
     */
    private void handleAccept(SelectionKey key) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.configureBlocking(false);

        //将连接好的客户端通道注册到多路复用选择器上,并设置为数据读取准备就绪
        socketChannel.register(selector,SelectionKey.OP_READ);
    }

    /**
     * 处理数据读取请求
     * @param key
     */
    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        ByteBuffer bb = ByteBuffer.allocate(1024);

        int readBytes = socketChannel.read(bb);
        if(readBytes > 0){
            bb.flip();
            byte[] bytes = new byte[bb.remaining()];
            bb.get(bytes);

            String body = new String(bytes,"UTF-8");
            System.out.println("the time server receive order :" + body);
            String currentTime = QUERY_TIME_COMMAND.equals(body) ?
                    new Date(System.currentTimeMillis()).toString() : "bad order";
            doWrite(socketChannel,currentTime);

            //如果数据读取长度为0,说明客户端已经关闭了连接
        }else if(readBytes < 0){
            key.cancel();
            socketChannel.close();
        }
    }

    /**
     * 往指定通道输出内容
     * @param socketChannel
     * @param content
     */
    private void doWrite(SocketChannel socketChannel, String content) throws IOException {
        byte[] byteContent = content.getBytes();
        ByteBuffer bb = ByteBuffer.allocate(byteContent.length);
        bb.put(byteContent);
        bb.flip();
        socketChannel.write(bb);

    }

}
